/*
 * WorkbenchWindow.java
 *
 * Created on 2008/09/23 +0900
 *
 * $Revision: 38 $
 * $Date: 2008-10-11 08:48:45 +0000 (Sat, 11 Oct 2008) $
 */

package org.gikolet.framework.view;

import java.util.Enumeration;
import java.util.Vector;

import org.gikolet.framework.ui.Display;
import org.gikolet.framework.ui.Shell;
import org.gikolet.framework.util.Assert;

/**
 * @author tetsutaro (latest modification by $Author: tetsutaro.ss $)
 * @version $Revision: 38 $ $Date: 2008-10-11 08:48:45 +0000 (Sat, 11 Oct 2008) $
 */
public class WorkbenchWindow {
    private Display display;
    private Shell shell;
    private Vector views;

    private ViewLayout viewLayout;

    public WorkbenchWindow(Display display, String text, ViewLayout viewLayout) {
	Assert.isNotNull(display, "display");
	Assert.isNotNull(viewLayout, "viewLayout");

	this.display = display;
	this.shell = new Shell(text);

	this.views = new Vector();

	setViewLayoutCore(viewLayout);
    }

    public void setVisible(boolean visible) {
	Shell currentShell = this.display.getShell();
	if (visible) {
	    if (currentShell != this.shell) {
		this.display.setShell(this.shell);
	    }
	} else {
	    if (currentShell == this.shell) {
		this.display.setShell(this.shell);
	    }
	}
    }

    public boolean isVisible() {
	return this.display.getShell() == this.shell;
    }

    public void addView(View view) {
	Assert.isNotNull(view, "view");

	if (!this.views.contains(view)) {
	    this.views.addElement(view);
	    this.viewLayout.addLayoutView(view);
	}
    }

    public void removeView(View view) {
	Assert.isNotNull(view, "view");

	if (this.views.removeElement(view)) {
	    this.viewLayout.removeLayoutView(view);
	}
    }

    public void setViewLayout(ViewLayout viewLayout) {
	setViewLayoutCore(viewLayout);
    }

    // コンストラクタでも使うため
    private void setViewLayoutCore(ViewLayout viewLayout) {
	Assert.isNotNull(viewLayout, "viewLayout");

	ViewLayout oldViewLayout = this.viewLayout;

	if (oldViewLayout != null) {
	    Enumeration e = this.views.elements();
	    while (e.hasMoreElements()) {
		oldViewLayout.removeLayoutView((View) e.nextElement());
	    }
	    oldViewLayout.finalizeLayout();
	    oldViewLayout.setContainer(null);

	    this.shell.removeAll();
	}

	this.viewLayout = viewLayout;

	viewLayout.setContainer(this.shell);
	viewLayout.initializeLayout();

	Enumeration e = this.views.elements();
	while (e.hasMoreElements()) {
	    viewLayout.addLayoutView((View) e.nextElement());
	}
    }
}
